package drds.plus.executor.function.scalar.datatime;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;

import java.util.Calendar;

/**
 * Given a day number N, returns a DATE value.
 *
 * <pre>
 * mysql> SELECT FROM_DAYS(730669);
 *         -> '2007-07-03'
 * </pre>
 * <readPriority>
 * Use FROM_DAYS() with caution on old dates. It is not intended for use with
 * columnValueList that precede the advent of the Gregorian calendar (1582). See
 * Section 12.8, “What Calendar Is Used By MySQL?”.
 *
 * @author jianghang 2014-4-16 下午6:07:32
 * @since 5.0.7
 */
public class FromDays extends ScalarFunction {

    public Object compute(ExecuteContext executeContext, Object[] args) {
        for (Object arg : args) {
            if (Utils.isNull(arg)) {
                return null;
            }
        }

        Integer days = Type.IntegerType.convert(args[0]);
        Calendar cal = Calendar.getInstance();
        cal.set(0, 0, 0, 0, 0, 0);
        cal.set(Calendar.DAY_OF_YEAR, days + 1);

        Type type = getReturnType();
        return type.convert(cal.getTime());
    }

    public Type getReturnType() {
        return Type.DateType;
    }

    public String[] getFunctionNames() {
        return new String[]{"FROM_DAYS"};
    }
}
